﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using PlatWL.Data;
using PlatWL.Services.Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace PlatWL.Services.Services
{
    public class AuthManage
    {
        //后台用户登录
        public void AuthLogin(ref Msg_Result msg, string UserName, string password)
        {
            string md5password =Tools.Common.Md5(password);
            var usr = new pt_auth_userb().GetEntityFirst(p => p.UserName == UserName && p.Password == md5password);
            if (usr == null)
            {
                msg.error = "用户名或密码不正确";
            }
            else
            {
                //为用户生成登录凭证
                string token = Tools.Common.GuID();
                new pt_auth_tokenb().Insert(new pt_auth_token()
                {
                    Client = usr.Client,
                    UserID = usr.ID,
                    Token = token,
                    TokenTime = DateTime.Now,
                    ExpireTime = DateTime.Now.AddDays(1),
                    ISAdmin = 1
                });

                msg.result = token;

            }

        }


        //token获取
        public pt_auth_token GetToken(string token)
        {
            return new pt_auth_tokenb().GetEntity(p => p.Token == token);
        }


        //用户管理首页菜单

        #region 后台用户信息
        public void User_List(ref Msg_Result msg, int Client, Msg_Page page, pt_auth_user auth_user)
        {
            int total = 0;
            DataTable dt = new pt_auth_userb().GetDataPager("pt_auth_user u left join pt_auth_role r on u.RoleID=r.ID", "u.*,r.RoleName", page.pagesize, page.pageindex, " u.CRTime desc ", " u.IsSuper=0 ", ref total);
            msg.result = dt;
        }
        public void User_Add(ref Msg_Result msg, int Client, pt_auth_user auth_user, pt_auth_user new_user)
        {
            if (Client == 0)
            {
                if (new_user.ID == 0)
                {
                    new_user.Client = 0;
                    new_user.Password = Tools.Common.Md5(new_user.Password);
                    new_user.CRTime = DateTime.Now;
                    new_user.CRUser = auth_user.ID;
                    new_user.Points = 0;
                    new_user.Status = 1;
                    new_user.IsSuper = 0;

                    new pt_auth_userb().Insert(new_user);
                }
                else
                {
                    var oldUser = new pt_auth_userb().GetEntity(p => p.ID == new_user.ID);
                    oldUser.TrueName = new_user.TrueName;
                    oldUser.Telephone = new_user.Telephone;
                    oldUser.RoleID = new_user.RoleID;
                    //1.判断是否修改密码
                    if (!string.IsNullOrEmpty(new_user.Password))
                    {
                        oldUser.Password= Tools.Common.Md5(new_user.Password);
                    }
                    new pt_auth_userb().Update(oldUser);
                }
            }
           
        }
        public void User_Model(ref Msg_Result msg, int Client, int ID)
        {
            var usr = new pt_auth_userb().GetEntity(d => d.ID == ID);
            if (usr != null)
            {
                usr.Password = "";
                msg.result = usr;
            }
        }
        public void User_Del(ref Msg_Result msg, int Client, pt_auth_user auth_user, int ID)
        {
            new pt_auth_userb().Delete(d => d.ID == ID && d.UserName != "admin" && d.UserName != "super");
        }
        #endregion

        #region 权限管理

        /// <summary>
        /// 后台首页菜单
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="auth_user"></param>
        public void GetMenu(ref Msg_Result msg, int Client, pt_auth_user auth_user)
        {
            if (auth_user.IsSuper == 1)
            {
                DataTable menuDT = new pt_auth_menub().GetDTByCommand("select * from pt_auth_menu where TopID=0 and ISVAL='1' order by Sort");
                menuDT.Columns.Add("SubItem", typeof(DataTable));
                foreach (DataRow dr in menuDT.Rows)
                {
                    dr["SubItem"] = new pt_auth_menub().GetDTByCommand("select * from pt_auth_menu where ISVAL='1' and TopID=" + dr["ID"].ToString() + " order by Sort");
                }
                msg.result = menuDT;
            }
            else
            {
                if (auth_user.RoleID.HasValue)
                {
                    DataView menuView = new DataView(new pt_auth_menub().GetDTByCommand("select m.ID,m.MenuTxt,m.MenuTip,m.MenuUrl,m.MenuIco,m.ISVAL,m.TopID,m.Sort,m.IsSys,h.RoleAuth as MenuAuth from pt_auth_menu m join pt_auth_roleauth h on m.ID=h.MenuID where h.RoleID ="+ auth_user.RoleID.Value + " and m.ISVAL = 1 and m.IsSys = 0"));
                    menuView.RowFilter = " TopID=0";
                    menuView.Sort = "Sort";

                    DataTable menuDT = menuView.ToTable();
                    menuDT.Columns.Add("SubItem", typeof(DataTable));
                    foreach (DataRow dr in menuDT.Rows)
                    {
                        menuView.RowFilter = " ISVAL='1' and TopID=" + dr["ID"].ToString();
                        menuView.Sort = "Sort";
                        dr["SubItem"] = menuView.ToTable();
                    }
                    msg.result = menuDT;
                }
            }

        }


        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="page"></param>
        /// <param name="auth_user"></param>
        public void Role_List(ref Msg_Result msg, int Client, Msg_Page page, pt_auth_user auth_user)
        {
            int total = 0;
            DataTable dt = new pt_auth_userb().GetDataPager("pt_auth_role", "*", page.pagesize, page.pageindex, " CRTime desc ", "1=1", ref total);
            msg.result = dt;
        }

        /// <summary>
        /// 角色MODEL
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="page"></param>
        /// <param name="auth_user"></param>
        /// <param name="id"></param>
        public void Role_Model(ref Msg_Result msg, int Client, Msg_Page page, pt_auth_user auth_user,int id)
        {
            msg.result = new pt_auth_roleb().GetEntity(p => p.ID == id);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="page"></param>
        /// <param name="auth_user"></param>
        /// <param name="id"></param>
        public void Role_Del(ref Msg_Result msg, int Client, Msg_Page page, pt_auth_user auth_user, int id)
        {
            new pt_auth_roleb().Delete(p => p.ID == id);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="auth_user"></param>
        /// <param name="new_role"></param>
        public void Role_Add(ref Msg_Result msg, int Client, pt_auth_user auth_user, pt_auth_role new_role)
        {
            if (Client == 0)
            {
                if (new_role.ID == 0)
                {
                    new_role.CRTime = DateTime.Now;
                    new_role.CRUser = auth_user.ID;

                    new pt_auth_roleb().Insert(new_role);
                }
                else
                {
                    new pt_auth_roleb().Update(new_role);
                }

                if (!string.IsNullOrEmpty(new_role.RoleAuth))
                {
                    string ids = "";
                    var rh = JsonConvert.DeserializeObject<List<pt_auth_roleauth>>(new_role.RoleAuth);
                    foreach (var v in rh)
                    {
                        if (ids == "")
                        {
                            ids = v.MenuID.ToString();
                        }
                        else
                        {
                            ids += "," + v.MenuID.ToString();
                        }
                        var role = new pt_auth_roleb().ExsSclarSql("select * from pt_auth_roleauth where RoleID='" + new_role.ID + "' and MenuID='" + v.MenuID + "' ");
                        if (role != "") //update
                        {
                            new pt_auth_roleb().ExsSclarSql(string.Format("update pt_auth_roleauth set RoleAuth='{0}' where RoleID='{1}' and MenuID='{2}' ", v.RoleAuth, new_role.ID, v.MenuID));
                        }
                        else //add
                        {
                            new pt_auth_roleb().ExsSclarSql(string.Format("insert into pt_auth_roleauth(RoleID,MenuID,RoleAuth) values('{0}','{1}','{2}')", new_role.ID, v.MenuID, v.RoleAuth));
                        }
                    }

                    new pt_auth_roleb().ExsSclarSql(string.Format("delete from pt_auth_roleauth where RoleID='{0}' and MenuID not in ({1}) ", new_role.ID, ids));
                }
            }

        }

        /// <summary>
        /// 角色设置的权限
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="auth_user"></param>
        /// <param name="ID"></param>
        public void Role_Auth(ref Msg_Result msg, int Client, pt_auth_user auth_user)
        {
            DataTable menuDT = new pt_auth_menub().GetDTByCommand("select * from pt_auth_menu where TopID=0 and ISVAL='1' and IsSys=0 order by Sort");
            menuDT.Columns.Add("SubItem", typeof(DataTable));
            foreach (DataRow dr in menuDT.Rows)
            {
                dr["SubItem"] = new pt_auth_menub().GetDTByCommand("select * from pt_auth_menu where ISVAL='1' and IsSys=0 and TopID=" + dr["ID"].ToString() + " order by Sort");
            }
            msg.result = menuDT;


        }
        #endregion

    }
}
